package cn.elwy.rcp.kit.yssuco.handler;

import java.io.File;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.part.ViewPart;

import cn.elwy.common.log.Logger;
import cn.elwy.common.log.LoggerFactory;
import cn.elwy.osgi.config.util.RcpPathSupport;
import cn.elwy.rcp.kit.yssuco.copy.DeployYssUco;
import cn.elwy.rcp.kit.yssuco.copy.UcoLogText;
import cn.elwy.rcp.kit.yssuco.views.KitView;

public class DeployJarHandler extends AbstractHandler {

	Logger logger = LoggerFactory.getLogger(getClass());

	String path = "data/";
	String fileName = "YSSUCO.json";

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		File workspacePath = RcpPathSupport.getInstance().getWorkspacePath();
		File file = new File(workspacePath, fileName);
		if (!file.exists()) {
			String installPath = RcpPathSupport.getInstance().getInstallPath();
			file = new File(installPath, fileName);
		}
		if (file.exists()) {
			DeployYssUco deployYssUco = new DeployYssUco(new UcoLogText(null));
			try {
				deployYssUco.handle(file.getAbsolutePath());
				return null;
			} catch (Throwable e) {
				IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
				MessageDialog.openInformation(window.getShell(), "错误", e.getMessage());
			}
		}
		try {
			showView(KitView.ID);
		} catch (Throwable e) {
			IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
			MessageDialog.openInformation(window.getShell(), "错误", e.getMessage());
		}
		return null;
	}

	/**
	 * 显示视图
	 * @param id 视图ID
	 * @throws Exception
	 */
	public static void showView(String id) throws Exception {
		if (id == null || id.trim().equals("")) {
			return;
		}
		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(id);
	}

	/**
	 * 关闭视图
	 * @param view 视图对象
	 */
	public static void hideView(ViewPart view) {
		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().hideView(view);
	}

	@Override
	public boolean isEnabled() {
		return true;
	}
}
